<script setup lang="ts">
import CustomDialog from '@/components/CustomDialog/CustomDialog.vue'

import { useTeamLists } from '@/mixins/TeamManagement/MixinTeamLists'

import type { ScheduleScheme, ShiftUnit } from '@/types'
import { schedulingApi } from '@/api'

const emits = defineEmits<{
  (e: 'to-prev'): void
  (e: 'save-success'): void
}>()

const info = defineModel<{
  scheduleSchemeId?: ScheduleScheme['id']
  scheduleSchemeName: ScheduleScheme['name']
  shiftUnitId: ShiftUnit['id']
  shiftUnitName: ShiftUnit['name']
  shiftUnitDetails: ShiftUnit['details']
  teams: ScheduleScheme['team']
}>({
  required: true,
})

const title = computed(() => {
  return info.value.scheduleSchemeId ? '编辑' : '新增'
})

const dialogRef = ref<InstanceType<typeof CustomDialog>>()

const {
  loading,
  lists,
  pagination,
  getLists: getTeamLists,
} = useTeamLists()

/**
 * 将 lists 转换为 { id: name } 的对象
 * @type ScheduleScheme['team']
 */
const teamLists = computed<ScheduleScheme['team']>(() => {
  return unref(lists).map(v => ({
    id: v.id,
    name: v.name,
  }))
})

/**
 * @override
 */
pagination.pageSize = 8

const showPagination = computed(() => {
  return pagination.total > pagination.pageSize
})

const prevDisabled = computed(() => {
  return pagination.pageNumber === 1
})
const nextDisabled = computed(() => {
  return (
    pagination.pageNumber * pagination.pageSize
    >= pagination.total
  )
})
const minPickTeamsLength = computed(() => {
  return (info.value.shiftUnitDetails || []).length
})
const shiftDetailsString = computed(() => {
  return (info.value.shiftUnitDetails || [])
    .map(
      v =>
        `${v.name} ${v.time} ${
          v.isCrossDay ? '（跨天）' : ''
        }`,
    )
    .join('；')
})
const checkedTeams = computed(() => {
  return info.value.teams
})
const checkedCountClass = computed(() => {
  const m = unref(checkedTeams).length
  const n = (unref(minPickTeamsLength) || 0) + 1
  if (m < n / 2)
    return 'danger-checked'
  if (m < n)
    return 'warning-checked'
  return 'success-checked'
})

function clickPrev() {
  pagination.pageNumber--
  getTeamLists()
}
function clickNext() {
  pagination.pageNumber++
  getTeamLists()
}

function changeHandler() {}
function clickCloseTag(
  tag: ScheduleScheme['team'][number],
) {
  const index = info.value.teams.findIndex(
    v => v.id === tag.id,
  )
  if (index > -1) {
    info.value.teams.splice(index, 1)
  }
}

function toPrev() {
  close()
  emits('to-prev')
}

async function clickSave() {
  if (!info.value.scheduleSchemeName) {
    ElMessage.warning('请输入排班方案名称')
    return false
  }

  const shiftDetails = info.value.shiftUnitDetails || []
  if (
    !info.value.shiftUnitId
    || !info.value.shiftUnitName
    || shiftDetails.length === 0
  ) {
    ElMessage.warning('请选择班次单元')
    return false
  }

  if (
    !info.value.teams
    || info.value.teams.length < minPickTeamsLength.value
  ) {
    const count = info.value.shiftUnitDetails?.length
    ElMessage.warning(
      `请选择班组，同时班组数量要大于等于${
        count ? `${count}个` : '班次单元数'}`,
    )
    return false
  }

  const data = unref(info)
  try {
    await schedulingApi.saveOrUpdateSchedulingScheme({
      schedulingScheme: {
        id: data.scheduleSchemeId,
        name: data.scheduleSchemeName,
        shiftUnitId: data.shiftUnitId,
      },
      teamIdList: data.teams.map(v => v.id),
    })
    ElMessage.success('保存成功')
    close()
    emits('save-success')
  }
  catch (e) {}
  return true
}

function open() {
  // 选择班组对话框打开时重新请求班组信息，页码从为1开始
  pagination.pageNumber = 1
  getTeamLists()
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

onMounted(() => {
  getTeamLists()
})

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    :title="`${title}排班方案 - 选择班组`"
    width="740px"
  >
    <ElDescriptions border title="" :column="1">
      <ElDescriptionsItem label="方案名称" :min-width="80">
        {{ info.scheduleSchemeName }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="班次名称">
        {{ info.shiftUnitName }}
      </ElDescriptionsItem>
      <ElDescriptionsItem label="班次单元">
        <div class="align-center flex flex-wrap">
          <template
            v-for="(item, index) in info.shiftUnitDetails"
            :key="index"
          >
            <span style="margin-right: 5px;">{{ item.name }}</span>
            <span>{{ item.time }}</span>
            <span
              v-if="item.isCrossDay"
              style="color: var(--el-color-danger)"
            >
              （跨天）
            </span>
            ；
          </template>
        </div>
      </ElDescriptionsItem>
    </ElDescriptions>
    <div
      class="margin-top-sm flex"
      style="min-height: 25vh;"
    >
      <div
        v-loading="loading"
        class="padding-right-sm flex-shink-0 margin-right border-right"
      >
        <div class="shift-options" style="min-width: 100px">
          <ElCheckboxGroup
            v-model="(info.teams as any[])"
            @change="changeHandler"
          >
            <ElCheckbox
              v-for="option in teamLists"
              :key="option.id"
              :label="option"
            >
              {{ option.name }}
            </ElCheckbox>
          </ElCheckboxGroup>
        </div>
        <div
          v-if="showPagination"
          class="align-center margin-top-xs margin-bottom-sm flex justify-end"
        >
          <ElButton
            size="small"
            :disabled="prevDisabled"
            @click="clickPrev"
          >
            上一页
          </ElButton>
          <ElButton
            size="small"
            :disabled="nextDisabled"
            @click="clickNext"
          >
            下一页
          </ElButton>
        </div>
      </div>
      <div>
        <p>
          所选班组数量要大于等于{{
            info.shiftUnitDetails.length
          }}个
          <span :class="checkedCountClass">（已选{{ checkedTeams.length }}个）</span>
        </p>
        <div class="clearfix">
          <ElTag
            v-for="item in checkedTeams"
            :key="item.id"
            closable
            class="checked-teams"
            @close="clickCloseTag(item)"
          >
            {{ item.name }}
          </ElTag>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="width-fill flex">
        <ElButton type="primary" @click="toPrev">
          上一步
        </ElButton>
        <ElButton style="margin-left: auto" @click="close">
          取消
        </ElButton>
        <ElButton type="primary" @click="clickSave">
          保存
        </ElButton>
      </div>
    </template>
  </CustomDialog>
</template>

<style scoped>
.shift-options :deep(.el-checkbox-group) {
  display: block;
}
.shift-options :deep(.el-checkbox) {
  display: flex;
}
.checked-teams {
  float: left;
  margin-right: 10px;
  margin-bottom: 10px;
}
.checked-teams :deep(.el-tag__content) {
  max-width: 80px;
  text-overflow: ellipsis;
  overflow: hidden;
}
.danger-checked {
  color: var(--el-color-danger);
}
.warning-checked {
  color: var(--el-color-warning);
}
.success-checked {
  color: var(--el-color-success);
}
</style>
